package cn.ihoway.util;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;

/**
 * 写入/读取文件
 */
public class HowayIO {

    /**
     * 读取词典文件并写入set集合
     * @param path 词典文件路径
     * @param set 词典集合
     */
    public static void readFile(String path, Set<String> set) {
        HowayLog logger = new HowayLog(HowayIO.class);
        File file = new File(path);
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line = "";
            while((line = br.readLine()) != null) {
                set.add(line);
            }
            br.close();
        } catch (FileNotFoundException e) {
            logger.info("FileNotFoundException:"+e.getCause());
            logger.error(Arrays.toString(e.getStackTrace()));
        } catch (IOException e) {
            logger.error(Arrays.toString(e.getStackTrace()));
        }
    }

    /**
     *
     * @param dir 写入目录
     * @param name 文件名称
     * @param content 写入内容
     * @param append 是否以追加方式写入
     */
    public static void fileWriter(String dir,String name,String content,boolean append){
        HowayLog logger = new HowayLog(HowayIO.class);
        File fileDir = new File(dir);
        if(!fileDir.exists()){
            if(!fileDir.mkdirs()){
                logger.error(dir + "没有创建成功！");
            }
        }
        String path = dir + name;
        File file = new File(path);

        FileWriter fw;
        try {
            fw = new FileWriter(file,append);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.flush();
            bw.close();
        } catch (IOException e) {
            logger.error(Arrays.toString(e.getStackTrace()));
        }
    }


}
